What is globalthis?
The globalthis npm package provides a polyfill for the global `globalThis` object, which is a standard way to access the global object (e.g., `window` in browsers, `global` in Node.js) in a universal manner across different JavaScript environments. This package ensures that you can reliably use `globalThis` in environments where it might not be natively supported.
What are globalthis's main functionalities?
Polyfill for globalThis
This code snippet demonstrates how to polyfill the global `globalThis` object using the globalthis package. After requiring and invoking the package, you can reliably use `globalThis` in your code to refer to the global object.
require('globalthis')(); // This will polyfill globalThis if it doesn't exist
Other packages similar to globalthis
core-js
core-js is a modular standard library for JavaScript, which includes polyfills for ECMAScript up to the latest standards. It provides more comprehensive polyfills than globalthis, including polyfills for `globalThis`. It is more feature-rich but also larger in size compared to the focused functionality of globalthis.
es6-shim
es6-shim is a shim that provides compatibility shims so that legacy JavaScript engines behave as closely as possible to ECMAScript 6 (Harmony). It includes a polyfill for `globalThis` among many other features. Like core-js, it is more extensive than globalthis but also more heavyweight.
globalThis
An ECMAScript spec-compliant polyfill/shim for globalThis
. Invoke its "shim" method to shim globalThis
if it is unavailable.
This package implements the es-shim API interface. It works in an ES3-supported environment and complies with the spec proposal.
Most common usage:
var globalThis = require('globalthis')();
var globalThis = require('globalthis/polyfill')();
Example
var assert = require('assert');
var getGlobal = Function('return this');
assert.equal(globalThis, getGlobal());
var shimmedGlobal = require('globalthis').shim();
var shimmedGlobal = require('globalthis/shim')();
assert.equal(shimmedGlobal, globalThis);
assert.equal(shimmedGlobal, getGlobal());
var shimmedGlobal = require('globalthis').shim();
assert.equal(shimmedGlobal, globalThis);
assert.equal(shimmedGlobal, getGlobal());
Tests
Simply clone the repo, npm install
, and run npm test